package com.heima.wemedia.interceptor;


import com.heima.wemedia.utils.UserIdThreadUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Author：shi_xin_rui
 * @name：UserInterceptor
 * @Date：2023/6/4 15:45
 */

@Component
public class UserInterceptor implements HandlerInterceptor {

    //拦截请求， 获取请求头中的userId， 如果userId非空， 存入到ThreadLocal中
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        if (!StringUtils.isBlank(userId)){
            UserIdThreadUtil.setUserId(Integer.parseInt(userId));
        }
        return true;
    }
    //移除ThreadLocal中存储的变量
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserIdThreadUtil.remove();
    }

}
